#include "controller.h"
#include <QMessageBox>
#include <QProcess>
Controller::Controller()
{
    QTextCodec* codec=QTextCodec::codecForLocale();
    QTextCodec::setCodecForTr(codec);

    QString GeeBoxPath1=QDir::homePath()+"/GeeBox";
    QString GeeBoxPath2=QDir::homePath()+"/.GeeBox";
    if(!QDir(tr(GeeBoxPath1.toStdString().c_str())).exists())
    {
        QDir dir;
        dir.mkpath(tr(GeeBoxPath1.toStdString().c_str()));
    }
    if(!QDir(tr(GeeBoxPath2.toStdString().c_str())).exists())
    {
        QDir dir;
        dir.mkpath(tr(GeeBoxPath2.toStdString().c_str()));
    }

    QString RunningFile=QDir::homePath()+"/"+".GeeBox/.Running";
    QString cmd=RunningFile;
    cmd.prepend("ps aucx|grep GeeBox > ");
    system(cmd.toStdString().c_str());
    cout<<cmd.toStdString()<<endl;

    QString RunningFile2=QDir::homePath()+"/"+".GeeBox/.Running2";
    QString cmd2=RunningFile2;
    cmd2.prepend(" > ").prepend(RunningFile).prepend("wc -l ");
    system(cmd2.toStdString().c_str());
    cout<<cmd2.toStdString()<<endl;

    QString cmd3=RunningFile;
    cmd3.prepend("ps aucx|grep 'GeeBox <defunct>' > ");
    system(cmd3.toStdString().c_str());
    cout<<cmd3.toStdString()<<endl;

    QString RunningFile3=QDir::homePath()+"/"+".GeeBox/.Running3";
    QString cmd4=RunningFile3;
    cmd4.prepend(" > ").prepend(RunningFile).prepend("wc -l ");
    system(cmd4.toStdString().c_str());
    cout<<cmd4.toStdString()<<endl;

    QFile RFile(RunningFile2);
    int tmp1;
    if(RFile.open(QFile::ReadOnly))
    {
        QTextStream in(&RFile);
        if(!in.atEnd())
            in>>tmp1;
        cout<<tmp1<<endl;
    }
    RFile.close();
    QFile RFile2(RunningFile3);
    int tmp2;
    if(RFile2.open(QFile::ReadOnly))
    {
        QTextStream in(&RFile2);
        if(!in.atEnd())
            in>>tmp2;
        cout<<tmp2<<endl;
    }
    RFile2.close();

    if((tmp1-tmp2)>1)
    {
        MMg=new MyMessageBox();
        MMg->setIcon(QMessageBox::Critical);
        MMg->setWindowTitle(tr("以有一个程序在运行"));
        MMg->setText(tr("已经有一个GeeBox程序在运行，如果您想启动新的GeeBox程序，请先退出原来的GeeBox程序"));
        MMg->exec();

        closeTimer.start(2000);
        connect(&closeTimer,SIGNAL(timeout()),qApp,SLOT(quit()));
        return;
    }

    log=NULL;
    wt=NULL;
    Ab=NULL;
    UserInfo=NULL;
    MMg=NULL;
    wn=NULL;
    useAge=0;
    iconUpdateFinished=0;
    tsf_sock=0;
    ctl_sock=0;

    //暂时不使用，用来读取用户配置信息获取主文件夹
//    QString geeboxrcFile=QDir::homePath()+"/.geeboxrc";
//    QFile geeboxrc(geeboxrcFile);
//    if(geeboxrc.open(QFile::ReadOnly))
//    {
//        QTextStream out(&geeboxrcFile);
//        out>>curDir;
//    }
//    QDir::setCurrent(curDir);



    //设置当前文件夹
    QDir::setCurrent("/usr/share/GeeBox");
    //curDir=QDir::homePath();
    //curDir.append("/GeeBox");
    curDir=QDir::currentPath();

    //QMessageBox::information(0,"tt",curDir);

    QString autoStartFile=QDir::homePath()+"/.GeeBox/.atuoStart";
    if(!QFile::exists(autoStartFile))
    {
        QString startDir=QDir::homePath()+"/.config/autostart";
        QDir dir;
        dir.mkpath(startDir);
        QString cmd="cp /usr/share/applications/GeeBox.desktop "+startDir+"/";
        system(cmd.toStdString().c_str());
        QFile tmpFile(autoStartFile);
        tmpFile.open(QFile::WriteOnly);
        tmpFile.close();
    }
    QString startFile=QDir::homePath()+"/.config/autostart/GeeBox.desktop";
    if(QFile::exists(startFile))
    {
        this->autoStart=1;
    }
    else
        autoStart=0;
    //设置图标
    passwdFilePath=QDir::homePath()+"/.GeeBox/.passwd";
    normalIconPath=curDir+"/icon";
    upIconPath=curDir+"/upIcon";
    startIcon=curDir+"/startIcon";

    QIcon normalIcon(normalIconPath);
    QIcon SIcon(startIcon);

    setWindowIcon(normalIcon);


    //设置托盘图标，信号和槽，托盘菜单
    trayIcon=new QSystemTrayIcon(this);
    trayIcon->setIcon(SIcon);
    trayIcon->setToolTip("geeBox");
    actionOpenHomeFodler=new QAction(tr("打开主文件"),this);
    connect(actionOpenHomeFodler,SIGNAL(triggered()),this,SLOT(openHomeFodler()));
    actionOpenWeb=new QAction(tr("打开我们的主页"),this);
    connect(actionOpenWeb,SIGNAL(triggered()),this,SLOT(openWeb()));
    actionHelp=new QAction(tr("帮助"),this);
    connect(actionHelp,SIGNAL(triggered()),this,SLOT(help()));
    actionSuggestion=new QAction(tr("反馈"),this);
    connect(actionSuggestion,SIGNAL(triggered()),this,SLOT(suggestion()));
    if(autoStart==1)
        actionAutoStart=new QAction(tr("取消开机自动运行"),this);
    else
        actionAutoStart=new QAction(tr("设为开机自动运行"),this);
    connect(actionAutoStart,SIGNAL(triggered()),this,SLOT(autoStartSetting()));
    //
    actionUserInformation=new QAction(tr("用户容量"),this);
    connect(actionUserInformation,SIGNAL(triggered()),this,SLOT(userInformation()));
    actionAboutUs=new QAction(tr("关于我们"),this);
    connect(actionAboutUs,SIGNAL(triggered()),this,SLOT(aboutUs()));
    actionLogout=new QAction(tr("注销"),this);
    connect(actionLogout,SIGNAL(triggered()),this,SLOT(logout()));
    actionQuit=new QAction(tr("退出"),this);
    connect(actionQuit,SIGNAL(triggered()),this,SLOT(Quit()));
//    actionProcess=new QAction("Process",this);
//    connect(actionProcess,SIGNAL(triggered()),this,SLOT(process()));

    trayIconMenu=new QMenu(this);
    trayIconMenu->addAction(actionOpenHomeFodler);
    trayIconMenu->addAction(actionOpenWeb);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(actionUserInformation);
    moreMenu=trayIconMenu->addMenu(tr("更多"));
    moreMenu->addAction(actionHelp);
    moreMenu->addAction(actionSuggestion);
    moreMenu->addAction(actionAboutUs);

    trayIconMenu->addSeparator();
    trayIconMenu->addAction(actionAutoStart);
    trayIconMenu->addAction(actionLogout);
    trayIconMenu->addAction(actionQuit);
    //trayIconMenu->addAction(actionProcess);


    trayIcon->setContextMenu(trayIconMenu);
    connect(trayIcon,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
    connect(&IconTimer,SIGNAL(timeout()),this,SLOT(setTrayIconFinished()));
    trayIcon->show();


    //读取passwd文件，判断是否自动登录
    wait=new Watting();
    wait->toHide();
        QFile file(passwdFilePath);
        if(file.open(QFile::ReadWrite))
        {
            QTextStream in(&file);
            int t;
            in>>t;
            file.close();
            if(t!=1)
            {
                QString tmpDir=QDir::homePath();
                tmpDir.append("/.GeeBox");
                log=new Login(tmpDir);
                connect(log,SIGNAL(startWait()),this,SLOT(startWaittingDialog()));
                connect(log,SIGNAL(waitFinish()),this,SLOT(finishWaittingDialog()));
                connect(log,SIGNAL(hasloged(int,QString)),this,SLOT(init(int,QString)));
                log->show();
            }
            else
            {
                autoLogin();
            }
        }

}

//打开用户主目录
void Controller::openHomeFodler()
{
    QString tmpDir=homeDir;
    tmpDir.prepend("'").append("'");
    QString tmp="gnome-open "+tmpDir;
    system(tmp.toStdString().c_str());
}

//用户注销时候的函数
void Controller::logout()
{
    if(wt->isSendingData==1)
    {
        if(wn==NULL)
        {
            wn=new Warnning();
            wn->type=1;
            connect(wn,SIGNAL(quitButton()),this,SLOT(quitRightOn()));
            connect(wn,SIGNAL(logoutButton()),this,SLOT(logoutRightOn()));
            connect(wn,SIGNAL(cancelButton()),this,SLOT(cancelQuit()));
            wn->show();
        }
        else
        {
            wn->type=1;
            wn->show();
        }
    }
    else
    {
        wt->Running=0;
        this->setDirReadOnly(homeDir);
        if(ctl_sock!=0)
        {
            cout<<"here"<<endl;
            ::close(ctl_sock);
        }
        if(wt->getTsf_socket()!=0)
        {
            this->tsf_sock=wt->getTsf_socket();
            cout<<tsf_sock<<endl;
            ::close(tsf_sock);
        }
        if(log==NULL)
        {
            log=new Login(curDir);
            log->show();
        }
        else
        {
            userExit();//用户退出
            log->show();
        }
    }
}
//关于我们窗口
void Controller::aboutUs()
{
    QUrl url("http://210.30.96.32/about.html");
    QDesktopServices::openUrl(url);
}

//暂时没有用的函数，用来表示上传进度
void Controller::process()
{

}
//没有用的函数，用来表示用户信息
void Controller::userInformation()
{
    if(UserInfo==NULL)
    {
        UserInfo=new UserInformation(userName);
        UserInfo->setUseage(useAge);
        UserInfo->show();
    }
    else
    {
        UserInfo->setUseage(useAge);
        UserInfo->show();
    }
}

//点击托盘图标的事件，默认是打开用户主文件夹
void Controller::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch(reason)
    {
    case QSystemTrayIcon::Trigger:
        openHomeFodler();
        break;
    case QSystemTrayIcon::DoubleClick:
        openHomeFodler();
        break;
    case QSystemTrayIcon::MiddleClick:
        openHomeFodler();
        break;
    default:
        ;
    }
}
//没有用的接口
void Controller::versionChanged()
{
}

//设置文件图标为正在更新
void Controller::setIconUpdate(QString filename)
{
    filename.append("'").prepend("'");
    QString tmp="/usr/share/GeeBox/emblem "+filename+" ubuntuone-updating"; 
    system(tmp.toStdString().c_str());
}

//设置文件图标为更新完成
void Controller::setIconFinished(QString filename)
{
    filename.append("'").prepend("'");
    QString tmp="/usr/share/GeeBox/emblem "+filename+" ubuntuone-synchronized";
    system(tmp.toStdString().c_str());
}

//用户登录验证成功后的同步本地文件的函数
void Controller::init(int ctl_sock1, QString UserName)
{
    //获取要监控的用户主文件夹
    userName=UserName;
    ctl_sock=ctl_sock1;
    QString userFile=QDir::homePath()+"/.GeeBox/"+UserName+"/"+UserName;
    cout<<"uerfile"<<userFile.toStdString()<<endl;
    QFile file(userFile);
    if(file.open(QFile::ReadOnly))
    {
        QTextStream out(&file);
        int tmp;
        QString tmpPasswd;
        out>>tmp;
        out>>tmpPasswd;
        out>>homeDir;
        cout<<homeDir.toStdString()<<endl;
    }
    file.close();                   //获取用户需要监控和存放文件的主目录，放在homeDir中
    this->setDirWriteable(homeDir);
     BoxIniter=new Initer(homeDir,UserName,ctl_sock,&FOL);
     connect(BoxIniter,SIGNAL(startInit()),this,SLOT(isUpdating()));
     connect(BoxIniter,SIGNAL(initFinished()),this,SLOT(startWatcher()));
     connect(BoxIniter,SIGNAL(upVersion(int)),this,SLOT(setVersion(int)));
     connect(BoxIniter,SIGNAL(sizeChanged(long)),this,SLOT(changeSize(long)));
     connect(BoxIniter,SIGNAL(ForceOffLineWatchStart()),this,SLOT(ForceOffLineWatcher()));
     BoxIniter->start();
}


//下载文件
void Controller::pull_file(const char *serverPath, const char *path)
{
    int tsf_sock = tcp_connect(SRV_IP, SRV_DATA_PORT);
    if( tsf_sock < 0 )
        {
            perror("connect");
            return;
        }

    //发送PUSH请求
    uint8_t request = DATA_PULL;
    if( write(tsf_sock,&request,sizeof(uint8_t)) < 0 )
    {
        perror("send request to 1235");
        return;
    }

    //发送用户名
    char usr_name[USR_LEN];
    strncpy(usr_name,userName.toStdString().c_str(),USR_LEN);
    if( writen(tsf_sock,usr_name,USR_LEN) < 0)
    {
        perror("send usr_name to 1235");
        return;
    }

    //发送目录
   // snprintf(log.str.path, PATH_LEN, "%s%s", SRV_ROOT, temp_path + i);

    if(writen(tsf_sock,serverPath,PATH_LEN) < 0 )
    {
        perror("send path to 1235");
        return;
    }

    //char path[PATH_LEN];
    //snprintf(path,PATH_LEN,"/home/%s/gsyncer%s",cuserid(NULL),log.str.path+strlen(SRV_ROOT));
    int fd_temp = ::open(path,O_WRONLY|O_TRUNC|O_CREAT);
    if( fd_temp < 0 )
    {
        cout<<"file "<<path<<" not exists now \n";
        return;

    }
    //Writen(tsf_sock,&head, sizeof(head));

    file_copy(fd_temp, tsf_sock);
    printf("%s download \n",path);
    ::close(fd_temp);
    ::close(tsf_sock);

}

//将服务器文件名转换为本地文件名
void Controller::decode_path(const char* from, char* to)
{
        int i = 0, counter = 0;
        for(; i < strlen(from) ; ++i)
        {
                if(from[i] == '/')
                        counter++;
                if( counter == 3 )
                        break;
        }
        char tmp[PATH_LEN-i];
        sprintf(tmp,from+i);
        QString downloadDir=homeDir+QString(tmp);
        sprintf(to,downloadDir.toStdString().c_str());
}

//用户退出函数，处理版本号问题
void Controller::Quit()
{
    if(wt->isSendingData==1)
    {
        cout<<"if 1"<<endl;
        if(wn==NULL)
        {
            wn=new Warnning();
            wn->type=0;
            connect(wn,SIGNAL(quitButton()),this,SLOT(quitRightOn()));
            connect(wn,SIGNAL(logoutButton()),this,SLOT(logoutRightOn()));
            connect(wn,SIGNAL(cancelButton()),this,SLOT(cancelQuit()));
            wn->show();
        }
        else
        {

            wn->type=0;
            wn->show();
        }
    }
    //this->setDirReadOnly(homeDir);
    else
    {
        this->setDirReadOnly(homeDir);
        wt->Running=0;
        wt->deleteLater();
        this->close();
        qApp->quit();
    }
}

//设置托盘图标为更新中
void Controller::isUpdating()
{
    this->iconUpdateFinished=0;
    IconTimer.start(2000);
    QIcon upIcon(upIconPath);
    trayIcon->setIcon(upIcon);
    trayIcon->show();
}
//设置托盘图标为更新完成
void Controller::updateFinished()
{
    this->iconUpdateFinished=1;
}
void Controller::setTrayIconFinished()
{
    if(this->iconUpdateFinished==1)
    {
        QIcon normalIcon(normalIconPath);
        trayIcon->setIcon(normalIcon);
        trayIcon->show();
        IconTimer.stop();
    }
}

//自动登录函数
void Controller::autoLogin()
{
    //获取用户名和密码
    QString passwd;
    QFile passwdFile(passwdFilePath);
    if(passwdFile.open(QFile::ReadOnly))
    {
        QTextStream out(&passwdFile);
        int tmp;
        out>>tmp;
        out>>userName;
        out>>passwd;
    }
    passwdFile.close();

    QString tmpDir=QDir::homePath();
    tmpDir.append("/.GeeBox");
    log=new Login(tmpDir);
    connect(log,SIGNAL(startWait()),this,SLOT(startWaittingDialog()));
    connect(log,SIGNAL(waitFinish()),this,SLOT(finishWaittingDialog()));
    connect(log,SIGNAL(hasloged(int,QString)),this,SLOT(init(int,QString)));
    log->userNameComboBox->setEditText(userName);
    log->passWdEdit->setText(passwd);
    log->checkBox->setChecked(true);
    log->checkBox_2->setChecked(true);
    log->login();
    //登录验证
//    ctl_sock = tcp_connect(SRV_IP,SRV_CTL_PORT);
//    if(ctl_sock < 0)
//    {
//        sleep(5);
//        ctl_sock = tcp_connect(SRV_IP,SRV_CTL_PORT);
//        if(ctl_sock<0)
//        {
//            sleep(5);
//            ctl_sock = tcp_connect(SRV_IP,SRV_CTL_PORT);
//            if(ctl_sock<0)
//            {
//                sleep(5);
//                ctl_sock = tcp_connect(SRV_IP,SRV_CTL_PORT);
//                if(ctl_sock<0)
//                {
//                    perror("login cant reach server");
//                    QErrorMessage err_msg;
//                    err_msg.setWindowTitle("Error:");
//                    err_msg.showMessage(tr("无法连接到服务器"));
//                    err_msg.exec();
//                    return;
//                }
//            }
//        }
//    }
//
//    //打包
//    ctl_pkg_t info;
//    info.type = LOGIN;
//    strncpy(info.str.id.usr,userName.toStdString().c_str(),USR_LEN);
//    strncpy(info.str.id.pwd,passwd.toStdString().c_str(),PWD_LEN);
//
//    //发送给服务器
//    if( writen(ctl_sock,&info,sizeof(ctl_pkg_t)) < 0 )
//    {
//        QErrorMessage err_msg(this);
//        err_msg.setWindowTitle("Error:");
//        err_msg.showMessage("Can't send user info to the server");
//        err_msg.exec();
//
//        ::close(ctl_sock);
//        return;
//    }
//
//    //读取服务器的应答
//    int8_t reply;
//    if( readn(ctl_sock,&reply,sizeof(reply)) < 0 )
//    {
//        QErrorMessage err_msg(this);
//        err_msg.setWindowTitle("Error:");
//        err_msg.showMessage("Can't read from the server");
//        err_msg.exec();
//
//        ::close(ctl_sock);
//        return;
//    }
//
//    //reply<0说明登录失败
//    if (reply != 0)
//    {
//        QErrorMessage err_msg(this);
//        err_msg.setWindowTitle("Error:");
//        err_msg.showMessage(tr("用户名或密码错误"));
//        err_msg.exec();
//
//        ::close(ctl_sock);
//        return;
//    }
//    init(ctl_sock,userName);
}

//递归删除文件夹中的东西
int Controller::dfs_rmdir(const char *path)
{
        struct stat info;
        if( stat(path,&info) < 0 )
        {
                perror("stat");
                return -1;
        }


        if( S_ISDIR(info.st_mode) )     //如果是目录  则递归删除
        {
                DIR *pre = opendir(path);
                if( pre == NULL  )
                {
                        perror("opendir");
                        return -1;
                }

                struct dirent *entry = readdir(pre);
                while(entry != NULL)
                {
                        if( strcmp(entry->d_name,".") == 0 ||
                                        strcmp(entry->d_name,"..") == 0 )
                        {
                                entry = readdir(pre);
                                continue;
                        }

                        string temp(path);
                        temp += "/";
                        temp += entry->d_name;

                        if( stat(temp.c_str(),&info) )
                        {
                                perror("stat");
                                return -1;
                        }

                        if(S_ISDIR(info.st_mode) )
                        {
                                dfs_rmdir(temp.c_str());
                        }
                        else
                        {
                                unlink(temp.c_str());
                        }

                        entry = readdir(pre);
                }
                closedir(pre);
                rmdir(path);
                return 0;

        }
        else                    //如果是文件  直接删除
        {
                return unlink(path);
        }
}

void Controller::userExit()
{

}

/*
  用来更新版本号的槽
  */
void Controller::upVersionFile()
{
    version++;
    cout<<version<<endl;
    QString version_path = QDir::homePath()+"/.GeeBox/"+userName+"/.version";
    cout<<version_path.toStdString()<<endl;
    QFile file(version_path);
    if(file.open(QFile::WriteOnly))
    {
        QTextStream out(&file);
        out<<version;
    }
}

/*
  给一个文件夹中的文件和文件夹递归添加徽标
  */
void Controller::setEmblemForDir(QString path)
{
    DIR* pdir;
    struct dirent *dir;
    setIconFinished(path);
    pdir=opendir(path.toStdString().c_str());
    while((dir=readdir(pdir))!=NULL)
    {
        if(dir->d_type&DT_DIR)
        {
            if(strcmp(dir->d_name,".")==0||strcmp(dir->d_name,"..")==0)
                continue;
            QString temp=QString(path)+'/'+QString(dir->d_name);
            setEmblemForDir(temp);
        }
        else
            {

            QString tmp=QString(path)+'/'+QString(dir->d_name);
            cout<<tmp.toStdString()<<endl;
            setIconFinished(tmp);
        }
    }
    closedir(pdir);
}
/*
  如果是删除一个文件夹事件，递归的将文件夹中在map（用于记录最后有那些文件要下载）中的
  文件从map中删除
  参数：dirName：文件夹名称
  */
void Controller::rmDirFromMap(const char *dirName)
{
    DIR* pdir;
    struct dirent *dir;
    pdir=opendir(dirName);
    while((dir=readdir(pdir))!=NULL)
    {
        if(dir->d_type&DT_DIR)
        {
            if(strcmp(dir->d_name,".")==0||strcmp(dir->d_name,"..")==0)
                continue;
            QString temp=QString(dirName)+'/'+QString(dir->d_name);
            rmDirFromMap(temp.toStdString().c_str());
        }
        else
            {
            QString tmp=QString(dirName)+'/'+QString(dir->d_name);
            if(initFliter.find(tmp)!=initFliter.end())
                initFliter.remove(tmp);
        }
    }
    closedir(pdir);
}


/*
  如果是移动一个文件夹事件，递归的将文件夹中在map（用于记录最后有那些文件要下载）中的
  文件进行重命名
  参数：path1：源文件夹名称
  参数：path2：目标文件夹名称
  */
void Controller::mvDirFromMap(const char* path1, const char *path2)
{
    DIR* pdir;
    struct dirent *dir;
    pdir=opendir(path1);
    while((dir=readdir(pdir))!=NULL)
    {
        if(dir->d_type&DT_DIR)
        {
            if(strcmp(dir->d_name,".")==0||strcmp(dir->d_name,"..")==0)
                continue;
            QString temp=QString(path1)+'/'+QString(dir->d_name);
            QString temp2=QString(path2)+'/'+QString(dir->d_name);
            mvDirFromMap(temp.toStdString().c_str(),temp2.toStdString().c_str());
        }
        else
            {
            QString tmp=QString(path1)+'/'+QString(dir->d_name);
            QString tmp2=QString(path2)+'/'+QString(dir->d_name);
            if(initFliter.find(tmp)!=initFliter.end())
            {
                initFliter[tmp2]=initFliter[tmp];
                initFliter.remove(tmp);
            }
        }
    }
    closedir(pdir);
}

/*
  把一个文件夹设置为只读
  */

void Controller::setDirReadOnly(QString dirName)
{
    DIR* pdir;
    struct dirent *dir;
    QString tmpDir=dirName;
    tmpDir.append("'").prepend("'");
    QString cmd="chmod a-w "+tmpDir;
    system(cmd.toStdString().c_str());
    pdir=opendir(dirName.toStdString().c_str());
    while((dir=readdir(pdir))!=NULL)
    {
        if(dir->d_type&DT_DIR)
        {
            if(strcmp(dir->d_name,".")==0||strcmp(dir->d_name,"..")==0)
                continue;
            QString temp=QString(dirName)+'/'+QString(dir->d_name);
            setDirReadOnly(temp);
        }
        else
        {
            QString temp=QString(dirName)+'/'+QString(dir->d_name);
            temp.prepend("'").append("'");
            QString cmd1="chmod a-w "+temp;
            system(cmd1.toStdString().c_str());
        }
    }
    closedir(pdir);
}

/*
  给一个文件夹及其子文件夹添加写权限
  */
void Controller::setDirWriteable(QString dirName)
{
    DIR* pdir;
    struct dirent *dir;
    QString tmpDir=dirName;
    tmpDir.append("'").prepend("'");
    QString cmd="chmod a+w "+tmpDir;
    system(cmd.toStdString().c_str());
    pdir=opendir(dirName.toStdString().c_str());
    while((dir=readdir(pdir))!=NULL)
    {
        if(dir->d_type&DT_DIR)
        {
            if(strcmp(dir->d_name,".")==0||strcmp(dir->d_name,"..")==0)
                continue;
            QString temp=QString(dirName)+'/'+QString(dir->d_name);
            setDirWriteable(temp);
        }
        else
        {
            QString temp=QString(dirName)+'/'+QString(dir->d_name);
            temp.prepend("'").append("'");
            QString cmd1="chmod a+w "+temp;
            system(cmd1.toStdString().c_str());
        }
    }
}


//开始监控，这个槽在接收到initer类传过来的初始化完成信号被触发，开始新建一个watcher对象，开始监控
void Controller::startWatcher()
{
    this->updateFinished();
    wt=new watcher(homeDir.toStdString(),ctl_sock,userName.toStdString(),useAge);
    connect(wt,SIGNAL(hasChanged()),this,SLOT(upVersionFile()));
    connect(wt,SIGNAL(setEmblemUpdating()),this,SLOT(isUpdating()));
    connect(wt,SIGNAL(setEmblemUpdated()),this,SLOT(updateFinished()));
    connect(wt,SIGNAL(sizeChanged(long)),this,SLOT(changeSize(long)));
    connect(wt,SIGNAL(sigOverSize(QString)),this,SLOT(slotOverSize(QString)));
    wt->start();
}

//设置版本号的槽，该槽的作用是在和服务器同步后，把本地版本号设置为服务器版本号
void Controller::setVersion(int real_version)
{
    version=real_version;
}

//当一个文件被更新时，对应的图标操作
void Controller::fileUpdating(QString fileName)
{
    cout<<"file updating"<<endl;
    this->isUpdating();
    QString tmp=fileName;
    QString tmp2=homeDir;
    tmp2.append("/");
    tmp.remove(tmp2);
    QStringList sList=tmp.split("/");
    tmp2=homeDir;
    for(QStringList::iterator it=sList.begin();it!=sList.end();it++)
    {
        tmp2.append("/");
        tmp2+=(*it);
        this->setIconUpdate(tmp2);
    }
}
//一个文件更新完成时候，对应的图标操作
void Controller::fileUpdated(QString fileName)
{
    cout<<"file updated"<<endl;
    this->updateFinished();
    QString tmp=fileName;
    QString tmp2=homeDir;
    tmp2.append("/");
    tmp.remove(tmp2);
    QStringList sList=tmp.split("/");
    tmp2=homeDir;
    for(QStringList::iterator it=sList.begin();it!=sList.end();it++)
    {
        tmp2.append("/");
        tmp2+=(*it);
        this->setIconFinished(tmp2);
    }
}

void Controller::changeSize(long tmp)
{
    useAge=tmp;
    cout<<useAge<<endl;
    if(UserInfo!=NULL)
    {
        UserInfo->setUseage(useAge);
    }
}

void Controller::slotOverSize(QString name)
{
    QString tmp=name;
    tmp.prepend("抱歉，由于容量限制，我们将不会同步");
    if(MMg==NULL)
    {
        MMg=new MyMessageBox();
        MMg->setIcon(QMessageBox::Critical);
        MMg->setWindowTitle(tr("容量限制"));
        MMg->setText(tr(tmp.toStdString().c_str()));
        MMg->exec();
    }
    else
    {
        MMg->setIcon(QMessageBox::Critical);
        MMg->setWindowTitle(tr("容量限制"));
        MMg->setText(tr(tmp.toStdString().c_str()));
        MMg->show();
    }
}

void Controller::autoStartSetting()
{
    if(autoStart==1)
    {
        QString cmd=QDir::homePath();
        cmd.prepend("rm ").append("/.config/autostart/GeeBox.desktop");
        cout<<cmd.toStdString()<<endl;
        system(cmd.toStdString().c_str());
        autoStart=0;
        actionAutoStart->setText(tr("设为开机自动运行"));
        if(MMg==NULL)
        {
            MMg=new MyMessageBox();
            MMg->setIcon(QMessageBox::Information);
            MMg->setWindowTitle(tr("开机自动运行"));
            MMg->setText(tr("已经取消开机自动运行"));
            MMg->exec();
        }
        else
        {
            MMg->setIcon(QMessageBox::Information);
            MMg->setWindowTitle(tr("开机自动运行"));
            MMg->setText(tr("已经取消开机自动运行"));
            MMg->show();
        }
    }
    else
    {
        QString startDir=QDir::homePath()+"/.config/autostart";
        QDir dir;
        dir.mkpath(startDir);
        QString cmd="cp /usr/share/applications/GeeBox.desktop "+startDir+"/";
        system(cmd.toStdString().c_str());
        autoStart=1;
        cout<<cmd.toStdString()<<endl;
        actionAutoStart->setText(tr("取消开机自动运行"));
        if(MMg==NULL)
        {
            MMg=new MyMessageBox();
            MMg->setIcon(QMessageBox::Information);
            MMg->setWindowTitle(tr("开机自动运行"));
            MMg->setText(tr("已经设置为开机自动运行"));
            MMg->exec();
        }
        else
        {
            MMg->setIcon(QMessageBox::Information);
            MMg->setWindowTitle(tr("开机自动运行"));
            MMg->setText(tr("已经设置为开机自动运行"));
            MMg->show();
        }
    }
}
void Controller::quitRightOn()
{
    this->setDirReadOnly(homeDir);
    wt->Running=0;
    wt->deleteLater();
    this->close();
    qApp->quit();
}
void Controller::logoutRightOn()
{
    wt->Running=0;
    this->setDirReadOnly(homeDir);

    //wt->clearWatcher();
    if(ctl_sock!=0)
    {
        cout<<"here"<<endl;
        ::close(ctl_sock);
    }
    if(wt->getTsf_socket()!=0)
    {
        cout<<"close data_soket"<<endl;
        this->tsf_sock=wt->getTsf_socket();
        cout<<tsf_sock<<endl;
        ::close(tsf_sock);
    }
    if(log==NULL)
    {
        log=new Login(curDir);
        log->show();
    }
    else
    {
        userExit();//用户退出
        this->setTrayIconFinished();
        log->show();
    }
}
void Controller::cancelQuit()
{

}
void Controller::test()
{
    cout<<"hhhhh"<<endl;
}
void Controller::ForceOffLineWatcher()
{
    connect(FOL,SIGNAL(startWatcher()),this,SLOT(offline()));
}
void Controller::offline()
{
    if(MMg==NULL)
    {
        MMg=new MyMessageBox();
        MMg->setIcon(QMessageBox::Critical);
        MMg->setWindowTitle(tr("被迫掉线"));
        MMg->setText(tr("您的帐号已在另一个地方登录，您已经被迫下线"));
        MMg->exec();
    }
    else
    {
        MMg->setIcon(QMessageBox::Critical);
        MMg->setWindowTitle(tr("被迫掉线"));
        MMg->setText(tr("您的帐号已在另一个地方登录，您已经被迫下线"));
        MMg->show();
    }
    this->quitRightOn();
}

void Controller::openWeb()
{
    QUrl url("http://210.30.96.32");
    QDesktopServices::openUrl(url);
}
void Controller::suggestion()
{
    QUrl url("http://tie.youdao.com/tl_-565922601391017394");
    QDesktopServices::openUrl(url);
}
void Controller::help()
{
    QUrl url("http://tie.youdao.com/tl_-565922601391017394");
    QDesktopServices::openUrl(url);
}
void Controller::startAutoLog()
{
    log->login();
    autoLogTimer.stop();
}
void Controller::startWaittingDialog()
{
    wait->startWait();
    wait->show();
}
void Controller::finishWaittingDialog()
{
    cout<<"hide"<<endl;
    wait->toHide();
}
